今日目標,透過 UserController 接收請求後顯示註冊頁面,並簡單地使用 Thymeleaf。
package com.example.user;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@GetMapping("/register")
public String viewRegisterPage() {
return "register";
}
}
@Controller
:controller 聲明,讓程式知道他是 controller,才能做請求分發
@GetMapping
或是 @PostMapping
註解的函式回傳的是「模板名稱」,所以上述的 code 是回傳 register.html,而非 register 字串@RestController
註解 class,它要回傳的就是一個字串,通常會用在 API 頁面上,很少會單純回傳一個字串,而是回傳一個物件(Object),並使其自動轉換成 JSON 的字串並顯示到頁面上@GetMapping("/register")
:透過 get method 請求,並且 url 是 /register
,就會執行用此宣告的函式
/
,這表示根目錄,也就是單純只有主機名稱(host name)@ComponentScan
,整個檔案內容會是:
package com.example.cards;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan({
"com.example",
})
@EntityScan({
"com.example",
})
public class CardsApplication {
public static void main(String[] args) {
SpringApplication.run(CardsApplication.class, args);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/register">
<input type="email" placeholder="Email" />
<input type="text" placeholder="Username" />
<input type="password" placeholder="Password" />
<button type="submit">註冊</button>
</form>
</body>
</html>
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
# Thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.resources.static-locations=classpath:/static/
spring.resources.cache-period=0
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${name}"></h1>
<form method="post" action="/register">
<input type="email" id="email" name="email" placeholder="Email" />
<input type="text" id="username" name="username" placeholder="Username" />
<input type="password" id="password" name="password" placeholder="Password" />
<button type="submit">註冊</button>
</form>
</body>
</html>
xmlns:th="http://www.thymeleaf.org"
:只是用於告知 IntelliJ 有使用到 Thymeleaf,所以如果把這個拔掉,會發現下方 th: 變成紅色,但頁面並不會有所影響<h1 th:text="${name}"></h1>
:th 標籤語法,將在下方詳述,這邊是用 name 替換掉內容,其中 name 是從 controller 傳過去的變數名稱package com.example.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UserController {
@GetMapping("/register")
public String viewRegisterPage(Model model) {
model.addAttribute("name", "註冊");
return "register";
}
}
model.addAttribute("name", "註冊")
:用於傳遞變數到 template,第一個參數是變數名稱,第二個參數放這個變數存的值*{}
按照順序走發現頁面跑不出來QQ,後來發現要先把 Thymeleaf 加入依賴後, http://localhost:8080/register 頁面才正常顯示~